﻿using ELF.Gateway.Jwt;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Microsoft.Extensions.Http;

public static class HttpClientExtensions
{
    public static IHttpClientBuilder AddAuthToken(this IHttpClientBuilder builder)
    {
        builder.Services.TryAddTransient<HttpClientAuthorizationDelegatingHandler>();
        builder.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>();

        return builder;
    }

    private class HttpClientAuthorizationDelegatingHandler : DelegatingHandler
    {
        private readonly GatewayJwtService _jwtService;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public HttpClientAuthorizationDelegatingHandler(GatewayJwtService jwtService, IHttpContextAccessor httpContextAccessor)
        {
            _jwtService = jwtService;
            this._httpContextAccessor = httpContextAccessor;
        }

        public HttpClientAuthorizationDelegatingHandler(GatewayJwtService jwtService, IHttpContextAccessor httpContextAccessor, HttpMessageHandler innerHandler) : base(innerHandler)
        {
            _jwtService = jwtService;
            this._httpContextAccessor = httpContextAccessor;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var context = _httpContextAccessor.HttpContext ?? throw new InvalidOperationException("HttpContext is null");
            // 生成含用户ID的网关JWT
            var gatewayToken = _jwtService.CreateGatewayToken(context.User);
            // 替换请求头
            context.Request.Headers["Authorization"] = $"Bearer {gatewayToken}";
            return await base.SendAsync(request, cancellationToken);
        }
    }

}
